package com.gagakuai.domain.facts;

import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * @description: 事实数据集合
 * @author: houhong
 * @create: 2024-09-07 10:57
 **/
public class Facts implements Iterable<Fact<?>> {

    private static final Set<Fact<?>> facts = new HashSet<>();


    @Override
    public Iterator<Fact<?>> iterator() {
        return null;
    }


    public <T> void put(String name, T value) {

        Objects.requireNonNull(name, "name must not be null");
        Objects.requireNonNull(value, "value must not be null");

        Fact<?> fact = getFact(name);
        if (fact == null) {
            facts.remove(fact);
        }
        add(new Fact<T>(name, value));
    }

    public void add(Facts facts) {
        facts.forEach(this::add);
    }

    public <T> void add(Fact<T> fact) {

        Fact<?> exists = getFact(fact.getName());
        if (exists != null) {
            facts.remove(fact);
        }
        facts.add(fact);
    }

    public <T> T get(String factName) {


        Fact<?> fact = getFact(factName);
        if (fact == null) return null;

        return (T) fact.getValue();
    }


    public Fact<?> getFact(String factName) {

        Objects.requireNonNull(factName, "name must not be null");

        return facts.stream()
                .filter(fact -> StringUtils.equalsIgnoreCase(factName, fact.getName()))
                .findFirst()
                .orElse(null);
    }

    public Map<String, Object> asMap() {

        Map<String, Object> map = new HashMap<>();

        for (Fact<?> fact : facts) {
            map.put(fact.getName(), fact.getValue());
        }
        return map;
    }

    public Set<Fact<?>> getFacts() {
        return facts;
    }


}
